//
//  MessageManager.m
//  Message
//
//  Created by Fanty on 13-12-17.
//  Copyright (c) 2013年 Fanty. All rights reserved.
//

#import "MessageManager.h"
#import "MessageParser.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "ApiConstant+Message.h"
#import <ChamleonSDK/CApplication.h>
#import <FMDatabase.h>
#import <IsolatedStorageDB/DBStorageHelper.h>
#import <Module/DataCenter+Cube.h>
#import <Module/CubesModel.h>
#import <MainModuleSDK/MainModule.h>
#import <MainModuleSDK/AsyncTask.h>
#import "MessageModel.h"

@interface MessageManager()

-(void)startTimer:(BOOL)callNow;

-(void)sendFeedBack:(NSArray*)array;

-(BOOL)fillMessageLists:(NSArray*)list;

-(void)syncFinish:(BOOL)apnsNotify;

@end

@implementation MessageManager{
    AsyncTask* task;
    NSTimer* timer;
}


-(void)cancel{
    [task cancel];
    task=nil;
    [timer invalidate];
    timer=nil;
}

-(void)createNotification{
    NSString* username=[DataCenter defaultCenter].username;
    DBStorageData* data=[[DBStorageHelper standandStorage] storageDataWithModuleIdentifier:@"Message"];
    data.identifier=username;
    FMDatabase* database=[data openDatabase];
    [database open];
    FMResultSet* resultSet=[database executeQuery:@"select * from message"];
    
    CubeModel* sysModel=[[DataCenter defaultCenter] finidInstallCubeModule:@"com.foss.message.record"];
    sysModel.messageCount=0;
    MessageModel* messageModel=[[MessageModel alloc] init];

    
    while([resultSet next]){
        messageModel.messageId=[resultSet stringForColumn:@"id"];
        messageModel.title=[resultSet stringForColumn:@"title"];
        messageModel.content=[resultSet stringForColumn:@"content"];
        messageModel.messageType=[resultSet stringForColumn:@"messageType"];
        messageModel.receiveTime=[resultSet dateForColumn:@"receiveTime"];
        messageModel.isRead=[resultSet boolForColumn:@"isRead"];
        messageModel.moduleIdentifer=[resultSet stringForColumn:@"moduleIdentifer"];
        messageModel.moduleName=[resultSet stringForColumn:@"moduleName"];
        messageModel.announceId=[resultSet stringForColumn:@"announceId"];
        messageModel.moduleBadge=[resultSet intForColumn:@"moduleBadge"];
        messageModel.busiDetail=[resultSet intForColumn:@"busiDetail"];

        if(!messageModel.isRead){
            sysModel.messageCount++;
            if([messageModel.moduleIdentifer length]>0){
                CubeModel* cubeModel=[[DataCenter defaultCenter] finidInstallCubeModule:messageModel.moduleIdentifer];
                cubeModel.messageCount++;
                cubeModel.moduleBadge = messageModel.moduleBadge;
            }
        }
    }
    [database close];
    
    [self syncMessage];
}





-(void)syncMessage{
    [self cancel];
    MainModule* mainModule=(MainModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Main"];
    ASIHTTPRequest* request=[ASIHTTPRequest requestWithURL:[[ApiConstant defaultConstant] messageListURL]];
    task=[mainModule asyncWithOperation:request parser:[[MessageParser alloc] init]];
    __block MessageManager* objSelf=self;
    [task setFinishBlock:^{
        [objSelf syncFinish:NO];
        
    }];
}

-(void)syncMessageById:(NSString*)messageId{
    [self cancel];
    MainModule* mainModule=(MainModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Main"];
    ASIHTTPRequest* request=[ASIHTTPRequest requestWithURL:[[ApiConstant defaultConstant] messageByIdURL:messageId]];
    task=[mainModule asyncWithOperation:request parser:[[MessageParser alloc] init]];
    __block MessageManager* objSelf=self;
    [task setFinishBlock:^{
        [objSelf syncFinish:YES];
    }];

}

-(void)syncFinish:(BOOL)apnsNotify{
    NSArray* list=[task result];
    task=nil;
    if ([list count] > 0){
        BOOL existSecurity=[self fillMessageLists:list];
        if(apnsNotify && existSecurity){
            [[NSNotificationCenter defaultCenter] postNotificationName:@"Cube_SecurityUpdated" object:nil];
        }
        [self sendFeedBack:list];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Cube_MessageUpdated" object:nil];
    }
    else{
        [self startTimer:NO];
    }
}

-(NSArray*)messageGroupList{
    
    
    DataCenter* dataCenter=[DataCenter defaultCenter];
    
    DBStorageData* data=[[DBStorageHelper standandStorage] storageDataWithModuleIdentifier:@"Message"];
    data.identifier=dataCenter.username;
    FMDatabase* database=[data openDatabase];
    [database open];

    FMResultSet* resultSet=[database executeQuery:@"select moduleIdentifer,moduleName,isRead from Message"];

    NSMutableArray* array=[[NSMutableArray alloc] initWithCapacity:2];
    while([resultSet next]){
        MessageGroupModel* model=nil;
        NSString* moduleIdentifer=[resultSet stringForColumnIndex:0];
        for(MessageGroupModel* _model in array){
            if([_model.moduleIdentifer isEqualToString:moduleIdentifer]){
                model=_model;
                break;
            }
        }
        if(model==nil){
            model=[[MessageGroupModel alloc] init];
            [array addObject:model];
        }
        model.moduleIdentifer=moduleIdentifer;
        model.moduleName=[resultSet stringForColumnIndex:1];
        BOOL isRead=[resultSet boolForColumnIndex:2];
        if(!isRead)
            model.unReadCount++;
        model.totalCount++;
        
    }
    
    
    return array;
}

-(NSArray*)messageList:(NSString*)moduleIdentifier{
    
    NSMutableArray* array=[[NSMutableArray alloc] initWithCapacity:2];
    
    NSString* username=[DataCenter defaultCenter].username;
    DBStorageData* data=[[DBStorageHelper standandStorage] storageDataWithModuleIdentifier:@"Message"];
    data.identifier=username;
    FMDatabase* database=[data openDatabase];
    [database open];
    FMResultSet* resultSet=[database executeQuery:[NSString stringWithFormat:@"select * from message where moduleIdentifer='%@' order by rowid desc",moduleIdentifier]];
    
    
    while([resultSet next]){
        MessageModel* messageModel=[[MessageModel alloc] init];
        messageModel.messageId=[resultSet stringForColumn:@"id"];
        messageModel.title=[resultSet stringForColumn:@"title"];
        messageModel.content=[resultSet stringForColumn:@"content"];
        messageModel.messageType=[resultSet stringForColumn:@"messageType"];
        messageModel.receiveTime=[resultSet dateForColumn:@"receiveTime"];
        messageModel.isRead=[resultSet boolForColumn:@"isRead"];
        messageModel.moduleIdentifer=[resultSet stringForColumn:@"moduleIdentifer"];
        messageModel.moduleName=[resultSet stringForColumn:@"moduleName"];
        messageModel.announceId=[resultSet stringForColumn:@"announceId"];
        messageModel.moduleBadge=[resultSet intForColumn:@"moduleBadge"];
        messageModel.busiDetail=[resultSet intForColumn:@"busiDetail"];
        [array addObject:messageModel];
        
        //暂时先这样，到时加返load more
        if([array count]>=200)break;
    }
    
    [database close];
    
    return array;
}

-(void)removeMesageById:(NSString*)messageId{
    NSString* username=[DataCenter defaultCenter].username;
    DBStorageData* data=[[DBStorageHelper standandStorage] storageDataWithModuleIdentifier:@"Message"];
    data.identifier=username;
    FMDatabase* database=[data openDatabase];
    [database open];
    [database executeUpdate:[NSString stringWithFormat:@"delete from message where id='%@' ",messageId]];
    [database close];
}

-(void)removeMessageByGroup:(NSString*)moduleIdentifier{
    NSString* username=[DataCenter defaultCenter].username;
    DBStorageData* data=[[DBStorageHelper standandStorage] storageDataWithModuleIdentifier:@"Message"];
    data.identifier=username;
    FMDatabase* database=[data openDatabase];
    [database open];
    [database executeUpdate:[NSString stringWithFormat:@"delete from message where moduleIdentifer='%@' ",moduleIdentifier]];
    [database close];
}

-(void)setIsReadMessageById:(NSString*)messageId{
    NSString* username=[DataCenter defaultCenter].username;
    DBStorageData* data=[[DBStorageHelper standandStorage] storageDataWithModuleIdentifier:@"Message"];
    data.identifier=username;
    FMDatabase* database=[data openDatabase];
    [database open];
    [database executeUpdate:[NSString stringWithFormat:@"update message set isRead=1 where id='%@' ",messageId]];
    [database close];
}

-(void)startTimer:(BOOL)callNow{
    [self cancel];
    timer=[NSTimer scheduledTimerWithTimeInterval:(callNow?3.0f:300.0f) target:self selector:@selector(syncMessage) userInfo:nil repeats:NO];
}

-(void)sendFeedBack:(NSArray*)array{
    [self cancel];
    
    NSMutableString* ids=[[NSMutableString alloc] initWithCapacity:2];
    [array enumerateObjectsUsingBlock:^(id obj,NSUInteger index,BOOL*stop){
        MessageModel* model=obj;
        [ids appendString:model.messageId];
        if(index<[array count]-1)
            [ids appendString:@","];
    
    }];
    
    MainModule* mainModule=(MainModule*)[[CApplication sharedApplication] moduleForIdentifier:@"Main"];
    ASIFormDataRequest* request=[mainModule requestWithURL:[[ApiConstant defaultConstant] receptURL]];
    request.timeOutSeconds=5.0f;
    request.persistentConnectionTimeoutSeconds=5.0f;
    
    [request setPostValue:ids  forKey:@"msgId"];
    [request setPostValue:[ApiConstant defaultConstant].appKey forKey:@"appId"];
    [request setRequestMethod:@"PUT"];

    task=[mainModule asyncWithOperation:request parser:nil];
    __block MessageManager* objSelf=self;
    [task setFinishBlock:^{
        
        [objSelf startTimer:YES];
        
    }];
}

-(BOOL)fillMessageLists:(NSArray*)list{

    BOOL existsSecurity=NO;
    DataCenter* dataCenter=[DataCenter defaultCenter];
    
    DBStorageData* data=[[DBStorageHelper standandStorage] storageDataWithModuleIdentifier:@"Message"];
    data.identifier=dataCenter.username;
    FMDatabase* database=[data openDatabase];
    [database open];
    
    CubeModel* sysModel=[[DataCenter defaultCenter] finidInstallCubeModule:@"com.foss.message.record"];

    [database beginTransaction];
    for(MessageModel* model in list){
        
        if ([model.messageType isEqualToString:@"SYS"])       //系统消息的话，提供一个identifier给它
        {
            model.moduleIdentifer = @"com.foss.message.record";
        }
        else if ([model.messageType isEqualToString:@"SECURITY"])       //权限更改的话，提供一个identifier给它
        {
            model.moduleIdentifer = @"com.foss.security.record";
            model.moduleName=model.title;
        }
        
        NSString* sql=[NSString stringWithFormat:@"insert into Message(id,title,content,messageType,receiveTime,isRead,moduleIdentifer,moduleName,announceId,moduleBadge,busiDetail) values(?,?,?,?,datetime('now'),0,?,?,?,%d,%d)",model.moduleBadge,model.busiDetail];
        
        if([database executeUpdate:sql,model.messageId,model.title,model.content,model.messageType,model.moduleIdentifer,model.moduleName,model.announceId]){
            sysModel.messageCount++;
            
            if([model.moduleIdentifer length]>0){
                CubeModel* cubeModel=[[DataCenter defaultCenter] finidInstallCubeModule:model.moduleIdentifer];
                cubeModel.messageCount++;
                cubeModel.moduleBadge = model.moduleBadge;
            }
            if(!existsSecurity && [model.messageType isEqualToString:@"SECURITY"]){
                existsSecurity=YES;
            }
        }
    }
    [database commit];
    [database close];
    
    return existsSecurity;
}



@end
